package com.iflytek.jzcpx.procuracy.ocr.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iflytek.jzcpx.procuracy.common.enums.CommonResultEnum;
import com.iflytek.jzcpx.procuracy.common.util.JSONUtil;
import com.iflytek.jzcpx.procuracy.ocr.dao.MetricDao;
import com.iflytek.jzcpx.procuracy.ocr.entity.Metric;
import com.iflytek.jzcpx.procuracy.ocr.service.MetricService;
import com.iflytek.jzcpx.procuracy.tools.common.PropUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class MetricServiceImpl extends ServiceImpl<MetricDao, Metric> implements MetricService {

    private static final Logger logger = LoggerFactory.getLogger(MetricServiceImpl.class);

    @Override
    public boolean updateByDataId(String dataId, CommonResultEnum commonResultEnum) {
        if (StringUtils.isBlank(dataId) || commonResultEnum == null) {
            return false;
        }

        LambdaQueryWrapper<Metric> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Metric::getDataId, dataId);
        List<Metric> metrics = list(wrapper);
        if (CollectionUtils.isEmpty(metrics)) {
            return false;
        }

        metrics = metrics.stream().filter(m -> m.getCostTime() == null).filter(m -> m.getEndMillis() == null).collect(
                Collectors.toList());
        if (CollectionUtils.isEmpty(metrics)) {
            return false;
        }
        if (CollectionUtils.size(metrics) > 1) {
            logger.warn("埋点数据重复!!! {}", JSONUtil.toStrDefault(metrics));
        }

        Metric metric = null;
        Integer updateType = PropUtils.getInt("metric_update_duplicate", 0);
        switch (updateType) {
            case 0:
                metric = metrics.get(0);
                break;
            case -1:
                metric = metrics.get(metrics.size() - 1);
                break;
            default:
                return false;
        }
        if (metric == null) {
            return false;
        }

        Date d = new Date();
        Metric entity = new Metric();
        entity.setId(metric.getId());
        entity.setUpdateTime(d);
        entity.setOcrEndTime(d);
        entity.setEndMillis(d.getTime());
        long costTime = d.getTime() - metric.getStartMillis();
        costTime = costTime < 0 ? 0 : costTime;
        entity.setCostTime(costTime);
        entity.setOcrResult(commonResultEnum.name());
        logger.info("更新指标统计数据 {}", entity);
        return updateById(entity);
    }

}
